import { AllChannelsResponse, Channel, ChannelResponse, ArticlesResponse } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import { http } from '@/utils/http'
const CHANNEL_KEY = 'geek-channels'

export const getUserChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    // 1. 在该 action 中，进行数据获取的逻辑判断，判断条件是用户是否登录
    const token = getState().login.token
    if (token) {
      // 2. 如果已登录，发送请求获取用户的频道列表数据
      const res = await http.get<ChannelResponse>('/user/channels')
      console.log('登录用户返回的频道数据', res)
      // dispatch 到redux 中
      dispatch({ type: '/home/getChannels', payload: res.data.data.channels })
    } else {
      // 3. 如果未登录，先判断本地缓存中有没有频道列表数据
      const localChannels = JSON.parse(localStorage.getItem(CHANNEL_KEY) ?? '[]') as Channel[]
      // 3.1. 如果本地有，拿到本地的频道列表数据
      if (localChannels.length > 0) {
        // dispatch 到redux 中
        console.log('dierci', localChannels)
        dispatch({ type: '/home/getChannels', payload: localChannels })
      } else {
        // 3.2. 如果本地没有，就发送请求获取默认的频道列表数据，并存储到本地缓存中
        const res = await http.get<ChannelResponse>('/user/channels')
        localStorage.setItem(CHANNEL_KEY, JSON.stringify(res.data.data.channels))
        // dispatch 到redux 中
        dispatch({
          type: '/home/getChannels',
          payload: res.data.data.channels
        })
      }
    }
  }
}
// 获取所有频道
export const getRestChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    // 获取所有频道数据
    const res = await http.get<AllChannelsResponse>('channels')
    // 我的频道数据
    const userChannels = getState().home.channels
    // 剩余（推荐）= 所有频道 - 我的频道
    const restChannels = res.data.data.channels.filter(
      item => userChannels.findIndex(item2 => item2.id === item.id) < 0
    )
    console.log('所有', res.data.data.channels)
    console.log('剩余', restChannels)
    // 将数据保存到reducer中
    dispatch({ type: '/home/getRestChannel', payload: restChannels })
  }
}
// 修改选中频道状态（页面UI）保存到redux中
export const toggleChannel = (id: number): RootThunkAction => {
  return dispatch => {
    // 修改reducer中的数据
    dispatch({ type: 'home/toggleChannel', payload: id })
  }
}
// 删除频道（登录和非登录）
export const delMyChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    // 登录
    const token = getState().login.token
    try {
      if (token) {
        const res = await http.delete(`/user/channels/${channel.id}`)
        console.log('删除频道res', res)
      } else {
        // 非登录，localStorage
        // 1 读出来
        const localChannels = JSON.parse(localStorage.getItem(CHANNEL_KEY) ?? '[]') as Channel[]
        // 2 修改
        const userChannels = localChannels.filter(item => item.id !== channel.id)
        // 3 写进去
        localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannels))
      }

      // 这里的逻辑是要在更新成功后才修改
      // 把更新后的数据状态存储到redux中
      dispatch({ type: 'home/delMyChannel', payload: channel })
    } catch (error) {
      // TODO 提示用更新失败
    }
  }
}
// 添加频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    const token = getState().login.token
    try {
      // 登录用户
      if (token) {
        const res = await http.patch('/user/channels', { channels: [channel] })
        console.log('添加频道res', res)
      } else {
        //非登录用户
        // 1 拿出来
        const localChannels = JSON.parse(localStorage.getItem(CHANNEL_KEY) ?? '[]')
        // 2 更新
        const userChannels = [...localChannels, channel]
        // 3 放进去
        localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannels))
      }

      dispatch({ type: 'home/addChannel', payload: channel })
    } catch (error) {
      // TODO 提示用户
    }
  }
}
export const getArticleList = (channelId: number, timestamp: string | number | null): RootThunkAction => {
  return async dispatch => {
    // 发起请求，获取文章列表数据
    const res = await http.get<ArticlesResponse>('/articles', {
      params: {
        channel_id: channelId,
        timestamp: timestamp
      }
    })

    console.log('文章res,action', res)
    // 把数据存储到redux中
    dispatch({
      type: 'home/getArticleList',
      payload: {
        channelId,
        articles: res.data.data
      }
    })
  }
}
